﻿using System;
using System.Net;
using System.Windows;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using System.Collections.Generic;

namespace TecHappy.WindowsPhone.Toolkit
{
    public class TecHappyVisualStateManager : VisualStateManager
    {
        protected override bool GoToStateCore(Control control, FrameworkElement templateRoot, string stateName, VisualStateGroup group, VisualState state, bool useTransitions)
        {
            return base.GoToStateCore(control, templateRoot, stateName, group, state, useTransitions);
        }

        public static bool GoToState(FrameworkElement element, string stateName, bool useTransitions)
        {
            System.Windows.VisualState state;
            VisualStateGroup group;
            if (stateName == null)
            {
                throw new ArgumentNullException("stateName");
            }

            IEnumerable<VisualStateGroup> visualStateGroups = GetVisualStateGroups(element).OfType<VisualStateGroup>();
            if (visualStateGroups == null)
            {
                return false;
            }

            if (!TryGetState(visualStateGroups, stateName, out group, out state))
            {
                if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(element))
                    throw new Exception("Unable to find state " + stateName + " for element " + element.Name);
                else
                    return false;
            }

            TecHappyVisualStateManager customVisualStateManager = GetCustomVisualStateManager(element) as TecHappyVisualStateManager;
            if (customVisualStateManager != null)
            {
                return customVisualStateManager.GoToStateCore(null, element, stateName, group, state, useTransitions);
            }

            return false;
        }

        internal static bool TryGetState(IEnumerable<VisualStateGroup> groups, string stateName, out VisualStateGroup group, out System.Windows.VisualState state)
        {
            var item = (from g in groups
                        from s in g.States.OfType<System.Windows.VisualState>()
                        where s.Name == stateName
                        select new
                        {
                            grp = g,
                            state = s
                        }).FirstOrDefault();
            if (item == null)
            {
                group = null;
                state = null;
                return false;
            }
            group = item.grp;
            state = item.state;
            return true;
        }

    }
}
